import sys
import time
from datetime import datetime
from datetime import timedelta

from PyQt5.QtCore import QObject, QThread, QDateTime, pyqtSignal
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QDialog, QLineEdit
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkiotda.v5.region.iotda_region import IoTDARegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkiotda.v5 import *
VERTUALDEVICE = False
DEBUG = True

class BackendThread(QThread):
    # equipStatus = pyqtSignal(str)
    # crossInfo = pyqtSignal(dict)
    checkFinishFlag = pyqtSignal(list)

    def __init__(self, equipmentList):
        super(QThread, self).__init__()
        self.equipmentList = equipmentList
        self.lastTime = 0

    def run(self):
        while True:
            equipOnlinelist = []
            for equipment in self.equipmentList:
                if equipment.getWorkStatus():
                    ak, sk, deviceId = equipment.getLoginInfo()
                    self.cloudInit(ak, sk, deviceId)
                    flag1, currentStatus = self.checkonline()
                    flag2, reportInfo = self.getcrossinfo()
                    if flag1 and flag2:
                        equipment.setInfoFlag(True)
                        equipment.setOnlineStatus(currentStatus)
                        equipment.setCrossInfo(reportInfo)
                        if currentStatus == "ONLINE":
                            equipOnlinelist.append(equipment.equipId)
                    else:
                        equipment.setInfoFlag(False)
                else:
                    equipment.setInfoFlag(False)
            self.checkFinishFlag.emit(equipOnlinelist)
            time.sleep(0.2)

    def cloudInit(self, ak, sk, deviceId):
        if VERTUALDEVICE:
            self.ak = "64EWXS9MKAQHXJ1R4PR4"  # "<YOUR AK>"
            self.sk = "HmSPDcDAJci2xiygQQNmqGTmZtkWs8BftBIJXNRa"  # "<YOUR SK>"
            self.deviceId = "6291c85cacbbb071175113c6_1653723364791"
        else:
            self.ak = ak # "NHWSTUWPK2N3PC2QCVEN" # "<YOUR AK>"
            self.sk = sk # "JZyO1HBjrSJauAuEgN8ZW1ioBbmCRw4UvvB0Jaje"  # "<YOUR SK>"
            self.deviceId = deviceId # "625bbdffecf9c41c382130bd_hispark_trafficlight"

        self.credentials = BasicCredentials(self.ak, self.sk)
        self.client = IoTDAClient.new_builder() \
            .with_credentials(self.credentials) \
            .with_region(IoTDARegion.value_of("cn-north-4")) \
            .build()

    # 查询当前设备状态
    def checkonline(self):
        try:
            request = ShowDeviceRequest()
            request.device_id = self.deviceId
            response = self.client.show_device(request)
            return True, response.status
        except:
            return False, "INTERNETERROR"

    # 获取设备上报的属性信息 返回信息上报的时间，设备当前模式，当前交通灯状态，以及当前车流量状态
    '''
    {"device_id": "625bbdffecf9c41c382130bd_hispark_trafficlight", "shadow": [{"service_id": "TrafficLight", "desired": {}, "reported": {"properties": {"ControlModule": "STRAIGHT_NORTH_SOUTH_GREEN", "AutoModule": "Closed", "AutoModuleGLedTC": 0, "AutoModuleYLedTC": 0, "AutoModuleRLedTC": 4, "HumanModule": "BEEP_OFF", "HumanModuleGledTC": 0, "HumanModuleRledTC": 30, "Straight_North_South": "Smooth", "SouthNorthTurnleft": "Congestion", "EastWestStraight": "Smooth", "SouthNorthStraight": "Smooth", "EastWestTurnleft": "Smooth", "NorthSouthStraight": "Smooth", "NorthSouthTurnleft": "Congestion", "WestEastStraight": "Smooth", "WestEastTurnleft": "Smooth", "CongestionDegree": "3280"}, "event_time": "20220531T123315Z"}, "version": 117763}]}
    '''
    def getcrossinfo(self):
        try:
            request = ShowDeviceShadowRequest()
            request.device_id = self.deviceId
            response = self.client.show_device_shadow(request)
            # print(response)
            if VERTUALDEVICE:
                equipShadow = response.shadow[1]
            else:
                equipShadow = response.shadow[0]
            infoControlModule = equipShadow.reported.properties["ControlModule"]
            infoAutoModule = equipShadow.reported.properties["AutoModule"]
            infoCongestionDegree = equipShadow.reported.properties["CongestionDegree"]
            infoTime = equipShadow.reported.event_time
            currentCongestion = self.str2list(infoCongestionDegree)
            if infoAutoModule == "Closed":
                currentModule = "ControlMode"
                currentLight = infoControlModule
            else:
                currentModule = "AutoMode"
                currentLight = infoAutoModule
            currentTimeGMT = datetime.strptime(infoTime,"%Y%m%dT%H%M%SZ") # 20220531T123315Z
            currentTimeBJT = currentTimeGMT + timedelta(hours=8)
            # if currentTimeBJT == self.lastTime:
            #     return {"status": "not_change"}
            # else:
            self.lastTime = currentTimeBJT
            if DEBUG:
                print({"status": "normal", "current_time": currentTimeBJT,
                        "current_mode": currentModule, "current_light": currentLight,
                        "current_congestion": currentCongestion})
            return True, {"status": "normal", "current_time": currentTimeBJT,
                    "current_mode": currentModule, "current_light": currentLight,
                    "current_congestion": currentCongestion}
        except:
            return False, {"status": "internet_error"}

    # 将congestion_str转换为列表
    def str2list(self, congestion):
        congestionInt = int(congestion)
        congestionList = self.convert(congestionInt, 3, [])
        while True:
            if len(congestionList) == 8:
                break
            else:
                congestionList.append(0)
        congestionList.reverse()
        return congestionList

    # 实现十进制数转换为x进制数，并返回一个列表
    def convert(self, n, x, b):
        if n < x:
            b.append(n)
            return b
        else:
            b.append(n % x)
            return self.convert(n // x, x, b)
